﻿<template>
  <s-layout title="民宿订单">
    <su-sticky bgColor="#fff">
      <su-tabs
        :list="tabMaps"
        :scrollable="false"
        @change="onTabsChange"
        :current="state.currentTab"
      ></su-tabs>
    </su-sticky>
    <s-empty
      v-if="state.pagination.total === 0"
      icon="/static/order-empty.png"
      text="暂无订单"
    ></s-empty>
    <view v-if="state.pagination.total > 0">
      <view
        class="bg-white order-list-card-box ss-r-10 ss-m-t-14 ss-m-20"
        v-for="order in state.pagination.data"
        :key="order.id"
      >
        <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20">
          <view class="order-no">{{ '订单号：' + order.orderSn }}</view>
          <view class="order-state ss-font-24 ml-auto" :class="formatOrderColor(order.status)">
            <text>{{ getHomestayOrderStatusName(order.status) }}</text>
          </view>
        </view>
        <view class="order-content ss-p-20">
          <view class="homestay-info ss-flex">
            <image
              class="homestay-image"
              :src="getHomestayImage(order)"
              mode="aspectFill"
            ></image>
            <view class="homestay-details ss-flex-1 ss-m-l-20">
              <view class="homestay-name ss-line-2">{{ order.homestayName }}</view>
              <view class="date-range ss-m-t-10">
                <text class="date-text">预订日期：{{ getAppointDatesText(order.appointDates) }}</text>
              </view>
              <view class="date-range ss-m-t-5">
                <text class="date-text">下单时间：{{ order.createTime }}</text>
              </view>
              <view class="days-price ss-flex ss-row-between ss-col-center ss-m-t-10">
                <text class="days-text">共{{ getAppointDaysCount(order.appointDates) }}晚</text>
                <text class="price-text">￥{{ order.totalAmount }}</text>
              </view>
            </view>
          </view>
          <view class="note-section ss-m-t-20" v-if="order.note">
            <text class="note-label">备注：</text>
            <text class="note-text">{{ order.note }}</text>
          </view>
        </view>
        <view class="order-card-footer ss-flex ss-col-center ss-p-x-20">
          <view class="ss-flex ss-col-center ml-auto">
            <button
              class="tool-btn ss-reset-button ui-BG-Main-Gradient"
              v-if="order.status === 0"
              @tap.stop="onPay(order)"
            >
              继续支付
            </button>
          </view>
        </view>
      </view>
    </view>

    <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadmore"
    />
  </s-layout>
</template>

<script setup>
import { computed, reactive } from 'vue';
import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
import sheep from '@/sheep';
import _ from 'lodash';

const pagination = {
  data: [],
  page: 1,
  total: 0,
  size: 10
};

const state = reactive({
  currentTab: 0,
  pagination: {
    data: [],
    page: 1,
    total: 0,
    size: 10
  },
  loadStatus: '',
});

const tabMaps = [
  {
    name: '全部',
    value: null,
  },
  {
    name: '待支付',
    value: 0,
  },
  {
    name: '已完成',
    value: 3,
  },
];

function formatOrderColor(status) {
  switch (status) {
    case 0:
      return 'warning-color';
    case 3:
      return 'success-color';
    default:
      return 'info-color';
  }
}

function getHomestayOrderStatusName(status) {
  switch (status) {
    case 0:
      return '待支付';
    case 3:
      return '已完成';
    default:
      return '未知状态';
  }
}

function onTabsChange(e) {
  if (state.currentTab === e.index) return;

  state.pagination = _.clone(pagination);
  state.currentTab = e.index;
  state.pagination.data = [];
  getOrderList();
}

async function getOrderList() {
  state.loadStatus = 'loading';
  
  try {
    const params = {
      page: state.pagination.page - 1,
      size: state.pagination.size,
    };
    
    if (tabMaps[state.currentTab].value !== null) {
      params.status = tabMaps[state.currentTab].value;
    }
    
    const res = await sheep.$api.noAuth.getHomestayOrders(params);
    
    if (res && res.content) {
      state.pagination.data = _.concat(state.pagination.data, res.content);
      state.pagination.total = res.totalElements || 0;
      
      if (state.pagination.page < (res.totalPages || 1)) {
        state.loadStatus = 'more';
      } else {
        state.loadStatus = 'noMore';
      }
    } else {
      state.loadStatus = 'noMore';
    }
  } catch (error) {
    state.loadStatus = 'noMore';
    sheep.$helper.toast('获取订单列表失败');
  }
}

function onCancel(orderId) {
  uni.showModal({
    title: '提示',
    content: '确定要取消订单吗？',
    success: async function (res) {
      if (res.confirm) {
        sheep.$helper.toast('取消订单功能暂未实现');
      }
    },
  });
}

function onPay(order) {
  sheep.$router.go('/pages/pay/index', {
    orderSN: order.orderSn,
    totalAmount: order.totalAmount,
    orderType: 'homestay'
  });
}

function getHomestayImage(order) {
  return 'https://git-open.oss-cn-shenzhen.aliyuncs.com/ruoyi-mall/uniapp/icons/homestay_default.png';
}

function getAppointDatesText(appointDatesStr) {
  try {
    if (!appointDatesStr) return '无预订日期';
    
    const appointDates = JSON.parse(appointDatesStr);
    const dates = Object.keys(appointDates).sort();
    
    if (dates.length === 0) return '无预订日期';
    if (dates.length === 1) return dates[0];
    if (dates.length === 2) return `${dates[0]} ~ ${dates[1]}`;
    
    return `${dates[0]} ~ ${dates[dates.length - 1]} 等${dates.length}天`;
  } catch (error) {
    return '日期格式错误';
  }
}

function getAppointDaysCount(appointDatesStr) {
  try {
    if (!appointDatesStr) return 0;
    
    const appointDates = JSON.parse(appointDatesStr);
    return Object.keys(appointDates).length;
  } catch (error) {
    return 0;
  }
}

function loadmore() {
  if (state.loadStatus !== 'noMore') {
    state.pagination.page++;
    getOrderList();
  }
}

onLoad(async (options) => {
  if (options.type) {
    const typeIndex = tabMaps.findIndex(tab => tab.value === parseInt(options.type));
    if (typeIndex !== -1) {
      state.currentTab = typeIndex;
    }
  }
  getOrderList();
});

onReachBottom(() => {
  loadmore();
});

onPullDownRefresh(() => {
  state.pagination = _.clone(pagination);
  getOrderList();
  setTimeout(function () {
    uni.stopPullDownRefresh();
  }, 800);
});
</script>

<style lang="scss" scoped>
.order-list-card-box {
  .order-card-header {
    height: 80rpx;

    .order-no {
      font-size: 26rpx;
      font-weight: 500;
    }
  }

  .order-content {
    .homestay-info {
      .homestay-image {
        width: 120rpx;
        height: 90rpx;
        border-radius: 8rpx;
        flex-shrink: 0;
      }

      .homestay-details {
        .homestay-name {
          font-size: 28rpx;
          font-weight: 500;
          color: #333;
          line-height: 40rpx;
        }

        .date-text {
          font-size: 24rpx;
          color: #666;
        }

        .days-price {
          .days-text {
            font-size: 24rpx;
            color: #666;
          }

          .price-text {
            font-size: 28rpx;
            font-weight: 500;
            color: #ff3000;
            font-family: OPPOSANS;
          }
        }
      }
    }

    .note-section {
      padding: 20rpx;
      background: #f8f9fa;
      border-radius: 8rpx;

      .note-label {
        font-size: 24rpx;
        color: #666;
      }

      .note-text {
        font-size: 24rpx;
        color: #333;
      }
    }
  }

  .order-card-footer {
    height: 100rpx;
    border-top: 1rpx solid #f0f0f0;
  }
}

.tool-btn {
  width: 160rpx;
  height: 55rpx;
  background: white;
  font-size: 26rpx;
  border-radius: 30rpx;
  margin-left: 10rpx;
  line-height: normal;

  &:last-of-type {
    margin-right: 0;
  }
}

.apply-btn {
  width: 160rpx;
  height: 55rpx;
  border-radius: 30rpx;
  font-size: 26rpx;
  border: 2rpx solid #dcdcdc;
  line-height: normal;
  margin-left: 10rpx;

  &:last-of-type {
    margin-right: 0;
  }
}

.warning-color {
  color: #faad14;
}

.success-color {
  color: #52c41a;
}

.info-color {
  color: #999999;
}
</style>
